path = require 'path'
fs = require 'fs'
async = require 'async'


module.exports.extConverter = (staticPath) ->
  convertExts = 
    'js' : 'coffee'
    'css' : 'styl'
  url = require 'url'
  (req, res, next) ->
    urlInfo = url.parse req.url
    file = path.join staticPath, urlInfo.pathname
    ext = path.extname(file).substring 1
    destExt = convertExts[ext]
    if destExt
      fs.exists file, (exists) ->
        if exists
          next()
        else
          req.url = req.url.replace ".#{ext}", ".#{destExt}"
          req.originalUrl = req.originalUrl.replace ".#{ext}", ".#{destExt}"
          next()
    else
      next()


module.exports.coffeeParser = (filePath) ->
  coffeeScript = require 'coffee-script'
  (req, res, next) ->
    process.nextTick next
    ext = path.extname req.url
    if ext == '.coffee'
      write = res.write
      end = res.end
      bufList = []
      bufLength = 0
      res.write = (chunk, encoding) ->
        bufList.push chunk
        bufLength += chunk.length
      res.end = (chunk, encoding) ->
        self = @
        if Buffer.isBuffer chunk
          bufList.push chunk
          bufLength += chunk.length
        if !bufLength
          if !res.headerSent
            end.call self
          return
        str = Buffer.concat(bufList, bufLength).toString encoding
        file = req.url.substring 0 , req.url.length - ext.length
        try
          js = coffeeScript.compile str
        catch err
          console.dir req.url
          console.dir err.location
          throw err if err
          return
        buf = new Buffer js, encoding
        res.header 'Content-Length', buf.length
        res.header 'Content-Type', 'application/javascript'
        write.call res, buf
        end.call res
      return


module.exports.stylusParser = (filePath) ->
  stylus = require 'stylus'
  nib = require 'nib'
  (req, res, next) ->
    process.nextTick next
    ext = path.extname req.url
    if ext == '.styl'
      file = path.join filePath, req.url
      write = res.write
      end = res.end
      bufList = []
      bufLength = 0
      res.write = (chunk, encoding) ->
        bufList.push chunk
        bufLength += chunk.length
      res.end = (chunk, encoding) ->
        self = @
        if Buffer.isBuffer chunk
          bufList.push chunk
          bufLength += chunk.length
        if !bufLength
          if !res.headerSent
            end.call self
          return
        str = Buffer.concat(bufList, bufLength).toString encoding
        async.waterfall [
          (cbf) ->
            stylus(str).set('filename', file).use(nib()).render cbf
            # stylus.render(str, {
            #   filename : file
            # }).use(nib()) cbf
          (css, cbf) ->
            buf = new Buffer css, encoding
            res.header 'Content-Length', buf.length
            res.header 'Content-Type', 'text/css'
            write.call res, buf
            end.call res
        ], (err) ->
          throw err if err
      return



#           function compile(str, path) {
#   return stylus(str)
#     .set('filename', path)
#     .set('compress', true)
#     .use(nib());
# }
